const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
const app = express();
const PORT = 7799;

app.use(bodyParser.json());

app.post('/login', async (req, res) => {
    const { code } = req.body;
    const appId = 'wx15a6265b98bf2da7';  // 替换为你的小程序 AppID
    const appSecret = '781bf79b5bd6ae127fc1a2e5f15ad687';  // 替换为你的小程序 AppSecret

    try {
        const response = await axios.get(`https://api.weixin.qq.com/sns/jscode2session`, {
            params: {
                appid: appId,
                secret: appSecret,
                js_code: code,
                grant_type: 'authorization_code'
            }
        });

        const { openid, session_key } = response.data;

        // 处理登录逻辑，比如生成用户 token 等
        res.json({
            success: true,
            openid,
            session_key
        });
    } catch (error) {
        console.error('获取 SESSION 失败', error);
        res.status(500).json({ success: false, message: '服务器错误' });
    }
});

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});